package com.demo.config;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MyRealm
 * @Description TODO
 * @Author Windy
 * @Date 2022/9/15 14:14
 * @Version 1.0
 **/
public class MyRealmMd5 extends AuthorizingRealm {
    public String getName(){
        return this.getClass().getName();
    }

    /**
     * 授权的方法
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        System.out.println(username);
        //根据用户名查询数据库中的权限
        List<String> permissions=new ArrayList<>();
        permissions.add("user:add");
        permissions.add("user:del");
        permissions.add("user:update");
        //创建AuthorizationInfo对象，其中包含权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        //添加这些信息所属于的角色
        info.addRole("role1");
        return info;
    }

    /**
     * 验证的方法
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取输入是用户名
        String username = (String) token.getPrincipal();
        System.out.println(username);
        char[] o = (char[]) token.getCredentials();
        System.out.println(o);

        //从数据库中查询出对应用户名的密码 （加密后的密码）
        String password="40aca64329b1143486a75be358f99da0";
        //将用户真正的密码信息进行封装  1.用户名 2.数据库查询出的真正密码（加密后） 3.盐值（用户名）4.自定义realm对象的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(username), getName());

        return info;
    }
}
